package com.huluobo.a2208kotlindouyindemo.shop

import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.blankj.utilcode.util.ToastUtils
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.gson.Gson
import com.huluobo.a2208kotlindouyindemo.adapter.CommonPagerAdapter
import com.huluobo.a2208kotlindouyindemo.databinding.ActivityDetailBinding
import com.huluobo.base.bean.CartBean
import com.huluobo.base.bean.GoodsBean
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class DetailActivity : BaseActivity<ActivityDetailBinding, ShopViewModel>() {
    private val tabEntities = arrayListOf<CustomTabEntity>()
    private lateinit var commonPagerAdapter: CommonPagerAdapter
    private val fragments = mutableListOf<Fragment>()
    private lateinit var goodsBean: GoodsBean
    override fun initData() {
        vm.getGoodsDetail(intent.getIntExtra(Const.PARAM_GOODS_ID, 0))
        vm.getGoodsDetailSuccess.observe(this) {
            binding.goods = it
            goodsBean = it
        }

        vm.addCartSuccess.observe(this) {
            ToastUtils.showLong("添加购物车成功")
        }
    }

    override fun initView() {
        tabEntities.clear()
        tabEntities.add(TabEntity("详情"))
        tabEntities.add(TabEntity("评论"))
        binding.detailTabLayout.setTabData(tabEntities)

        fragments.clear()
        fragments.add(DetailFragment())
        fragments.add(CommentFragment())

        commonPagerAdapter = CommonPagerAdapter(this, fragments)
        binding.detailVp2.adapter = commonPagerAdapter

        binding.detailTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                binding.detailVp2.currentItem = position
            }

            override fun onTabReselect(position: Int) {
            }
        })

        binding.detailVp2.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                binding.detailTabLayout.currentTab = position
            }
        })

        binding.detailAddToCart.setOnClickListener {
            val map = mutableMapOf<String, Int>()
            map[Const.PARAM_GOODS_ID] = goodsBean.id
            map[Const.PARAM_COUNT] = 1

            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            vm.addToCart(body)
        }

    }
}